/**
 * @author 35326
 * 2021/3/15 22:33
 *
 * 这个例子来自于《实战Java蒿并发程序设计第二版》
 * 说明stop()方法会引起数据不一致的问题
 */
public class ThreadNoEqualTest {

    private static User u = new User();
    public static class User{
        private int id;
        private String name;

        public User() {
            id=0;
            name="0";
        }

        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    '}';
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

    public static class ChangeObjectThread extends Thread{
        @Override
        public void run() {
            while(true){
                synchronized(u){
                    int v=(int)(System.currentTimeMillis()/1000);
                    u.setId(v);

                    //或者在这里做点其它事情
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    u.setName(String.valueOf(v));
                }

                Thread.yield();
            }

        }
    }

    public static class ReadObjectThread extends Thread{
        @Override
        public void run() {
            while(true){
                synchronized (u){
                    if(u.getId()!=Integer.parseInt(u.getName())){
                        System.out.println(u);
                    }
                }
                Thread.yield();
            }
        }
    }

    public static void main(String[] args) {
        new ReadObjectThread().start();
        while(true){
            Thread t = new ChangeObjectThread();
            t.start();
            try {
                Thread.sleep(150);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            t.stop();
        }
    }
}
